﻿using System;
using System.Globalization;
using System.Threading.Tasks;
using Casamiel.API.Application;
using Casamiel.API.Application.Services;
using Casamiel.Common;
using Casamiel.Domain;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using NLog;
using PaySharp.Core;
using PaySharp.Wechatpay;
using PaySharp.Wechatpay.Response;

namespace Casamiel.API.Controllers
{
	/// <summary>
	/// app微信支付
	/// </summary>
	/// 
	[ApiVersionNeutral]
    public class AppWxpayNotifyController : Controller
    {
        
        private readonly IPaymentRecordRepository _paymentRecordRepository;
        private readonly IIcApiService _iicApiService;
        private readonly IUserLogRepository _userLog;
        private readonly NLog.ILogger logger = LogManager.GetLogger("PayService");
        private readonly WxPayAppSettings _wxPay;
        private readonly IAllPayService _allPayService;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="paymentRecord">Payment record.</param>
        /// <param name="userLog">User log.</param>
        /// <param name="allPayService">All pay service.</param>
        /// <param name="iicApiService">Iic API service.</param>
        /// <param name="optionsSnapshot">Options snapshot.</param>
        public AppWxpayNotifyController(IPaymentRecordRepository paymentRecord,
            IUserLogRepository userLog, IAllPayService allPayService,
            IIcApiService iicApiService, IOptionsSnapshot<WxPayAppSettings> optionsSnapshot)
        {
            if (optionsSnapshot == null) {
                throw new ArgumentNullException(nameof(optionsSnapshot));
            }

            _paymentRecordRepository = paymentRecord;
            _userLog = userLog;
            _iicApiService = iicApiService;
            _wxPay = optionsSnapshot.Value;
            _allPayService = allPayService;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public async Task Index()
        {
            //Request.EnableRewind();
            var wechatpayMerchant = new Merchant {
                AppId = _wxPay.AppId,
                MchId = _wxPay.MchId,
                Key = _wxPay.Key,
                AppSecret = _wxPay.AppSecret,
                SslCertPath = _wxPay.SslCertPath,
                SslCertPassword = _wxPay.SslCertPassword,//"1233410002",
                NotifyUrl = _wxPay.NotifyUrl,
            };
            WechatpayGateway ga = new WechatpayGateway(wechatpayMerchant);
            IGateways gate = new Gateways();
            gate.Add(ga);
            Notify notify = new Notify(gate);
            notify.PaySucceed += Notify_PaymentSucceed;
            notify.UnknownNotify += Notify_UnknownNotify;
            notify.UnknownGateway += Notify_UnknownGateway;
            notify.RefundSucceed += Notify_RefundSucceed;
            // 接收并处理支付通知
            await notify.ReceivedAsync().ConfigureAwait(false);
        }

        private bool Notify_RefundSucceed(object arg1, RefundSucceedEventArgs arg2)
        {
            logger.Error("Notify_RefundSucceed:" + JsonConvert.SerializeObject(arg2));
            return true;
        }

        private bool Notify_UnknownNotify(object sender, UnKnownNotifyEventArgs e)
        {
            logger.Error("Notify_PaymentFailed:" + JsonConvert.SerializeObject(e));
            // 未知时的处理代码
            return false;
        }
        private void Notify_UnknownGateway(object arg1, UnknownGatewayEventArgs e)
        {
            logger.Error("Notify_UnknownGateway:" + JsonConvert.SerializeObject(e));
        }

        //private void Notify_PaymentFailed(object arg1, PayFailedEventArgs e)
        //{
        //    //throw new NotImplementedException();
        //    logger.Error("Notify_PaymentFailed:" + JsonConvert.SerializeObject(e));
        //}

        private bool Notify_PaymentSucceed(object arg1, PaySucceedEventArgs e)
        {
            // 支付成功时时的处理代码
            /* 建议添加以下校验。
             * 1、需要验证该通知数据中的OutTradeNo是否为商户系统中创建的订单号，
             * 2、判断Amount是否确实为该订单的实际金额（即商户订单创建时的金额），
             */
            if (e.GatewayType == typeof(WechatpayGateway)) {
                var wechatpayNotify = (NotifyResponse)e.NotifyResponse;
                logger.Trace($"OutTradeNo：{wechatpayNotify.OutTradeNo},TradeNo：{wechatpayNotify.TradeNo },{wechatpayNotify.TotalAmount / 100},{wechatpayNotify.MchId},{DateTime.Now.ToString("yyyyMMdd HH:mm:ss.fff", CultureInfo.CurrentCulture)}");

                var s = _allPayService.PayComplete(wechatpayNotify.OutTradeNo, wechatpayNotify.TradeNo, wechatpayNotify.TotalAmount / 100, wechatpayNotify.MchId);
                s.Wait();
                return s.GetAwaiter().GetResult();
                
                
                //同步通知，即浏览器跳转返回
            }
            //处理成功返回true
            return true;
        }
    }
}